<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class UserLogin extends Model
{
    protected $table = 'userloginlog';
    protected $default_table_name = 'userloginlog';

    private static $suffix;
    public $timestamps = false;

    public function __construct($suffix = null)
    {
        $this->setConnection('mysql_userlog');
        if (!$suffix) {
            $suffix = date('Ym');
        }
        $this->table = $this->default_table_name . $suffix;
        parent::__construct();
    }

    public function setTable($suffix)
    {
        $table = $this->default_table_name . $suffix;
        if(!Schema::hasTable($table)){
            $table = $this->default_table_name . date('Ym');
        }
        return $this->table = $table;
    }

    /**
     * 日登陆人数
     * @param $date
     * @param $server
     * @return int
     */
    public function getDayLoginedUsers($date, $server)
    {
        $this->setTable(date('Ym', $date));
        $res = $this->select(DB::raw('DISTINCT(userid)'))
            ->where('receivetime', 'like', date('Ymd', $date) . '%')
            ->where('servername', $server)
            ->get();

        return count($res);
    }

    /**
     * 日创建角色数量
     * @param $date
     * @param $server
     * @return int
     */
    public function getDayCreatedRoleUsers($date, $server)
    {
        $this->setTable(date('Ym', $date));
        $res = $this->select(DB::raw('DISTINCT(userid)'))
            ->where('receivetime', 'like', date('Ymd', $date) . '%')
            ->where('servername', $server)
            ->where('reserve0', 1)
            ->get();

        return count($res);
    }

    /**
     * 日创建角色数量
     * @param $date
     * @param $server
     * @return int
     */
    public function getDayCreatedRoleUsersPerHours($date, $server)
    {
        $this->setTable(date('Ym', $date));
        $data = $this->select(DB::raw('count(DISTINCT(userid)) as number, substring(receivetime,9,2) as hour'))
            ->where('receivetime', 'like', date('Ymd', $date) . '%')
            ->where('servername', $server)
            ->where('reserve0', 1)
            ->groupBy('hour')
            ->get()->toArray();
        $res = [];
        foreach ($data as $value) {
            $res[ $value['hour'] ] = (int)$value['number'];
        }
        $res['24'] = array_sum(array_values($res));

        return $res;
    }

    /**
     * 当前在线人数
     * @param $date
     * @param $server
     * @return int
     */
    public function getCurrentOnlineUsers($date, $server)
    {
        $this->setTable(date('Ym', $date));
        $res = $this->where('servername', $server)
            ->where('receivetime', 'like', date('YmdH', $date) . '%')
            ->orderBy('id', 'desc')->first();

        return $res ? $res['reserve1'] : 0;
    }

    /**
     * 日在线人数分布
     * @param $date
     * @param $server
     */
    public function getDayOnlineUsersPerHours($date, $server)
    {
        $this->setTable(date('Ym', $date));
        $res = $this->select(DB::raw('max(reserve1) as online_number, substring(receivetime,9,2) as hour'))
            ->where('receivetime', 'like', date('Ymd', $date) . '%')
            ->where('servername', $server)
            ->groupBy('hour')->orderBy('hour')
            ->get()
            ->toArray();

        $arr = [];
        foreach ($res as $r) {
            $arr[ $r['hour'] ] = $r['online_number'];
        }

        $hours = config('admin.data.hours');
        foreach ($hours as $h) {
            $arr[ $h ] = isset($arr[ $h ]) ? $arr[ $h ] : 0;
        }
        ksort($arr);

        return array_values($arr);
    }

    public function getRetainedUsersByDate($date, $server)
    {
        $date = date('Ymd', $date);
        $conditions = ['new', '+1 day', '+3 days', '+7 days', '+15 days', '+30 days'];
        $res = [];
        foreach ($conditions as $con) {
            switch ($con) {
                case 'new':
                    $tmp_date = strtotime($date);
                    $reserve0 = 1;
                    break;
                default:
                    $tmp_date = strtotime($date . $con);
                    $reserve0 = 0;
                    break;
            }
            $this->setTable(date('Ym', $tmp_date));
            $data = $this->select(DB::raw('DISTINCT(userid)'))
                ->where('receivetime', 'like', date('Ymd', $tmp_date) . '%')
                ->where('servername', $server)
                ->where('reserve0', $reserve0)
                ->get()->toArray();
            foreach ( $data as $d ) {
                $res[$con][] = $d['userid'];
            }

        }
//        print_r($res);
        $rate = [];
        $res['new'] = isset($res['new']) ? $res['new'] : [];
        foreach ($conditions as $con) {
            switch ($con) {
                case 'new':
                    $rate['new'] = isset($res['new']) ? count($res['new']) : 0;
                    break;
                default:
                    $num = isset($res[ $con ]) ? count(array_intersect($res['new'], $res[ $con ])) : 0;
                    $rate[] = $rate['new'] && $num ? round($num / count($res['new']), 4) * 100 . "%" : '';
                    break;
            }
        }
//        dd($rate);
        return $rate;
    }



    /**
     * 获得区服信息
     * @param $date
     * @return mixed
     */
    public function getServers($date)
    {
        $this->setTable($date);
        $servers = [];
        $res = $this->select('servername')->groupBy('servername')->get()->toArray();
        foreach ($res as $r) {
            $servers[] = $r['servername'];
        }

        return $servers;
    }
}
